import asyncio
import websockets
import json

# 维护一个全局的 WebSocket 连接列表
connected_clients = set()

# 启动倒计时事件处理
async def handle_start_countdown():
    message = json.dumps({'event': 'start_countdown'})
    if connected_clients:
        await asyncio.gather(*[client.send(message) for client in connected_clients])

async def handle_pause():
    message = json.dumps({'event': 'pause'})
    if connected_clients:
        await asyncio.gather(*[client.send(message) for client in connected_clients])

async def handle_reset():
    message = json.dumps({'event': 'reset'})
    if connected_clients:
        await asyncio.gather(*[client.send(message) for client in connected_clients])

async def handle_prevStage():
    message = json.dumps({'event': 'prevStage'})
    if connected_clients:
        await asyncio.gather(*[client.send(message) for client in connected_clients])

async def handle_nextStage():
    message = json.dumps({'event': 'nextStage'})
    if connected_clients:
        await asyncio.gather(*[client.send(message) for client in connected_clients])

async def handle_startLeft():
    message = json.dumps({'event': 'startLeft'})
    if connected_clients:
        await asyncio.gather(*[client.send(message) for client in connected_clients])

async def handle_startRight():
    message = json.dumps({'event': 'startRight'})
    if connected_clients:
        await asyncio.gather(*[client.send(message) for client in connected_clients])


async def websocket_handler(websocket):
    print("New connection from:", websocket.remote_address)
    connected_clients.add(websocket)
    try:
        async for message in websocket:
            data = json.loads(message)
            if data.get('event') == 'start_countdown':
                await handle_start_countdown()
            if data.get('event') == 'pause':
                await handle_pause()
            if data.get('event') == 'reset':
                await handle_reset()
            if data.get('event') == 'prevStage':
                await handle_prevStage()
            if data.get('event') == 'nextStage':
                await handle_nextStage()
            if data.get('event') == 'startLeft':
                await handle_startLeft()
            if data.get('event') == 'startRight':
                await handle_startRight()
    except websockets.ConnectionClosed:
        pass
    finally:
        connected_clients.remove(websocket)

# 启动 WebSocket 服务器
async def start_server():
    server = await websockets.serve(websocket_handler, "0.0.0.0", 8765)
    print("WebSocket 服务器启动，在 ws://0.0.0.0:8765")
    await server.wait_closed()

# 启动 WebSocket 服务器
if __name__ == '__main__':
    asyncio.run(start_server())
